<template>
  <div class="px-4 sm:px-8 md:px-16 lg:px-48 pt-4 w-full">
    <div class="flex flex-col">
      <n-card :title="'单位管理'">
        <template #header-extra>
          <div class="flex items-center">
            <n-button type="primary" @click="openCreateModal" class="px-6 mr-4">
              新增单位信息
            </n-button>
            <n-button type="success" @click="handleExport" :loading="isExporting" class="px-6">
              导出至Excel
            </n-button>
          </div>
        </template>

        <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-top: 16px; margin-bottom: 4px; align-items: center;">
          <div style="flex-shrink: 0; width: 280px;">
            <n-input v-model:value="searchTerm" placeholder="按单位名称、联系人搜索..." clearable @input="handleSearchDebounced"
              @clear="handleSearchDebounced">
              <template #prefix>
                <n-icon :component="SearchOutline" />
              </template>
            </n-input>
          </div>
          <div style="flex-shrink: 0; width: 200px;">
            <n-select v-model:value="filterUnitType" placeholder="选择单位类型" :options="unitTypeFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 200px;">
            <n-select v-model:value="filterUnitLevel" placeholder="选择单位级别" :options="unitLevelFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex: 1;" />
        </div>

        <div style="margin-top: 0;">
          <n-data-table ref="dataTableInstRef" :columns="columns" :data="unitStore.allUnits" :loading="unitStore.isLoading"
            :pagination="paginationConfig" remote @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange" @update:sorter="handleSorterChange" class="min-w-full"
            :scroll-x="2200" />
        </div>
      </n-card>
    </div>
  </div>

  <n-modal v-model:show="showModal" preset="card" :style="{ width: '800px' }" :title="modalTitle" size="huge"
    :bordered="false" :segmented="{ content: 'soft', footer: 'soft' }" closable @after-leave="handleModalClose">
    <unit-form ref="unitFormRef" :initial-data="editingUnit" @submit="handleFormSubmit" @cancel="closeModal" />
  </n-modal>
</template>

<script setup>
import { SearchOutline } from "@vicons/ionicons5";
import { h, ref, onMounted, computed } from "vue";
import {
  NIcon,
  NDataTable,
  NButton,
  useMessage,
  NInput,
  NSelect,
  NModal,
  NEllipsis,
  NCard,
  useDialog,
} from "naive-ui";
import UnitForm from '@/components/UnitForm.vue';

import { useUnitStore } from '@/stores/unitStore';
import { unitTypeOptions, unitLevelOptions } from '@/utils/constants';

const message = useMessage();
const dialog = useDialog();
const unitStore = useUnitStore();

const dataTableInstRef = ref(null);

// --- Modal control for UnitForm ---
const showModal = ref(false);
const modalTitle = ref('新增单位信息');
const editingUnit = ref(null);
const unitFormRef = ref(null);

const openCreateModal = () => {
  editingUnit.value = null;
  modalTitle.value = '新增单位信息';
  showModal.value = true;
};

const openEditModal = (rowData) => {
  editingUnit.value = { ...rowData };
  modalTitle.value = '编辑单位信息';
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
};

const handleModalClose = () => {
  if (unitFormRef.value && typeof unitFormRef.value.resetForm === 'function') {
    unitFormRef.value.resetForm();
  }
  editingUnit.value = null;
};

const handleFormSubmit = async (formData) => {
  // 立即关闭对话框，提升用户体验
  closeModal();

  try {
    if (editingUnit.value && editingUnit.value._id) {
      await unitStore.updateUnit(editingUnit.value._id, formData);
      message.success('单位信息更新成功');
    } else {
      await unitStore.addUnit(formData);
      message.success('单位信息新增成功');
    }

    // 重新获取当前页数据
    await fetchUnitsWithFilters();
  } catch (error) {
    console.error("表单提交失败:", error);
    message.error(editingUnit.value ? '更新失败，请重试' : '新增失败，请重试');
    // 不需要重新抛出错误，因为对话框已经关闭了
  }
};

// --- Data Mapping for Display ---
const unitTypeMap = Object.fromEntries(unitTypeOptions.map(opt => [opt.value, opt.label]));
const unitLevelMap = Object.fromEntries(unitLevelOptions.map(opt => [opt.value, opt.label]));

const getDisplayValue = (value, map, defaultValue = '未知') => map[value] || value || defaultValue;

// Options for filters
const unitTypeFilterOptions = ref(unitTypeOptions);
const unitLevelFilterOptions = ref(unitLevelOptions);



const createColumns = ({ onEdit, onDelete }) => {
  return [
    {
      title: '序号',
      key: 'tableId',
      width: 60,
      fixed: 'left',
      render: (_, index) => (paginationConfig.value.page - 1) * paginationConfig.value.pageSize + index + 1
    },
    { title: '单位名称', key: 'name', width: 200, sorter: true, fixed: 'left', ellipsis: { tooltip: true } },
    { title: '单位简称', key: 'shortName', width: 120, ellipsis: { tooltip: true } },
    { title: '标定代码', key: 'calibrationCode', width: 120, ellipsis: { tooltip: true } },
    { title: '回执代码', key: 'receiptCode', width: 120, ellipsis: { tooltip: true } },
    {
      title: '单位类型', key: 'unitType', width: 120, sorter: true,
      render: (row) => getDisplayValue(row.unitType, unitTypeMap)
    },
    {
      title: '单位级别', key: 'unitLevel', width: 120, sorter: true,
      render: (row) => getDisplayValue(row.unitLevel, unitLevelMap)
    },
    { title: '联系人', key: 'contactPerson', width: 100, ellipsis: { tooltip: true } },
    { title: '座机电话', key: 'landlinePhone', width: 140, ellipsis: { tooltip: true } },
    { title: '手机号码', key: 'mobilePhone', width: 140, ellipsis: { tooltip: true } },
    {
      title: '干部数量', key: 'cadreCount', width: 100, sorter: true,
      render: (row) => row.cadreCount || 0
    },
    {
      title: '备注', key: 'remarks', width: 200,
      render: row => h(NEllipsis, { tooltip: { style: { maxWidth: '300px' } } }, { default: () => row.remarks || 'N/A' })
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render(row) {
        return h('div', { style: 'display: flex; align-items: center; justify-content: center;' }, [
          h(NButton, { size: 'small', type: 'primary', ghost: true, onClick: () => onEdit(row), style: 'margin-right: 12px;' }, { default: () => '编辑' }),
          h(NButton, { size: 'small', type: 'error', ghost: true, onClick: () => onDelete(row) }, { default: () => '删除' })
        ]);
      },
    }
  ];
};

const handleDelete = (rowData) => {
  dialog.warning({
    title: '确认删除',
    content: `您确定要删除单位 "${rowData.name}" 吗？此操作不可恢复。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // 立即关闭对话框，异步执行删除操作
      performDelete(rowData);
      return true; // 立即关闭对话框
    }
  });
};

const performDelete = async (rowData) => {
  const loadingMessage = message.loading(`正在删除单位 ${rowData.name}...`, { duration: 0 });
  try {
    await unitStore.deleteUnit(rowData._id);
    loadingMessage.destroy();
    message.success(`单位 ${rowData.name} 已删除`);
    // 重新获取当前页数据
    await fetchUnitsWithFilters();
  } catch (error) {
    loadingMessage.destroy();
    message.error('删除失败，请重试');
    console.error("删除失败:", error);
  }
};

const columns = ref(createColumns({
  onEdit: openEditModal,
  onDelete: handleDelete,
}));

// --- Data Fetching, Filtering, Pagination, Sorting ---
const searchTerm = ref('');
const filterUnitType = ref([]);
const filterUnitLevel = ref([]);

const paginationConfig = computed(() => ({
  page: unitStore.pagination.page,
  pageSize: unitStore.pagination.limit,
  itemCount: unitStore.pagination.total,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
}));

const currentSortKey = ref(null);
const currentSortOrder = ref(false);
const isExporting = ref(false);



let searchDebounceTimer = null;
const handleSearchDebounced = () => {
  clearTimeout(searchDebounceTimer);
  searchDebounceTimer = setTimeout(() => {
    handleSearch();
  }, 300);
};

const handleSearch = async () => {
  await fetchUnitsWithFilters({ page: 1 });
};

// 获取带过滤条件的单位数据
const fetchUnitsWithFilters = async (paginationParams = {}) => {
  try {
    const params = {
      page: paginationParams.page || unitStore.pagination.page,
      pageSize: paginationParams.pageSize || unitStore.pagination.limit,
      search: searchTerm.value,
      unitType: filterUnitType.value?.length > 0 ? filterUnitType.value.join(',') : undefined,
      unitLevel: filterUnitLevel.value?.length > 0 ? filterUnitLevel.value.join(',') : undefined,
      sortBy: currentSortKey.value,
      sortOrder: currentSortOrder.value === 'ascend' ? 'asc' : currentSortOrder.value === 'descend' ? 'desc' : undefined,
    };

    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    await unitStore.fetchUnits(params);
  } catch (error) {
    console.error('获取单位数据失败:', error);
    message.error('获取数据失败');
  }
};

const applyTableFilters = async () => {
  await fetchUnitsWithFilters({ page: 1 });
};

const handlePageChange = async (page) => {
  await fetchUnitsWithFilters({ page });
};

const handlePageSizeChange = async (pageSize) => {
  await fetchUnitsWithFilters({ page: 1, pageSize });
};

const handleSorterChange = async (sorter) => {
  if (sorter && sorter.columnKey && sorter.order) {
    currentSortKey.value = sorter.columnKey;
    currentSortOrder.value = sorter.order;
  } else {
    currentSortKey.value = null;
    currentSortOrder.value = false;
  }
  await fetchUnitsWithFilters({ page: 1 });
};

// 导出功能
const handleExport = async () => {
  if (isExporting.value) return;

  try {
    isExporting.value = true;

    // 使用简单的 window.open 方式
    const exportUrl = 'http://localhost:3001/api/export/units';
    window.open(exportUrl, '_blank');

    message.success('单位信息导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请重试');
  } finally {
    isExporting.value = false;
  }
};

onMounted(async () => {
  try {
    // 加载第一页单位数据
    await fetchUnitsWithFilters();
  } catch (error) {
    console.error("Error during initial data fetch:", error);
    message.error("初始化数据加载失败");
  }
});
</script>